package cn.uniqueinfo.dp.aspect;

import cn.uniqueinfo.dp.service.ICtrlLogService;
import cn.uniqueinfo.dp.vo.CtrlLogVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-01-04 16:52:01
 * @description: 控制器方法操作日志
 */
@Slf4j
//@Aspect
//@Order(2)
@Component
public class CtrlMethodLogAspect {

    @Autowired private ICtrlLogService ctrlLogService;

    /** controller包下的当钱包和子孙包下的所有方法 */
    @Pointcut("execution(* cn.uniqueinfo.dp.controller..*(..))")
    public void methodLog() {}

    //    @Before("methodLog()")
    //    public void doBefore(JoinPoint joinPoint) {
    //        String logs = "---doBefore--"+joinPoint.getSignature().getDeclaringTypeName() + "." +
    // joinPoint.getSignature().getName();
    //        log.warn(logs);
    //    }

    @Around("methodLog()")
    public Object around(ProceedingJoinPoint pjp) {
        log.info("记录操作日志开始");
        Date date = new Date();
        CtrlLogVO item = new CtrlLogVO();
        item.setAddUId(1L);
        item.setAddUName("test");
        item.setAddDate(date);
        // MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        item.setCtrlName(pjp.getTarget().getClass().getName());
        String ctrlMethod = pjp.getSignature().getName();
        item.setCtrlMethod(ctrlMethod);
        // 获取参数
        Object[] args = pjp.getArgs();
        if (args == null || args.length == 0) {
            item.setCtrlMethodParam("");
        } else {
            String params = Arrays.toString(args);
            if (params.length() > 512) {
                params = params.substring(0, 512);
            }
            item.setCtrlMethodParam(params);
        }
        Object ob = null;
        try {
            ob = pjp.proceed();
        } catch (Throwable e) {
            log.error("记录操作日志错误");
            e.printStackTrace();
            // throw new UQException(0,"around","执行错误",e);
        }

        item.setActionTime((int) ((new Date()).getTime() - date.getTime()));
        this.ctrlLogService.insert(item);
        log.info("记录操作日志结束");
        return ob;
    }
}
